package edu.sandau.basic.controller;

import edu.sandau.basic.domain.User;
import edu.sandau.basic.global.GlobalEnum;
import edu.sandau.basic.service.UserService;
import edu.sandau.basic.vo.BasicMsg;
import edu.sandau.basic.vo.BasicMsgWithData;
import edu.sandau.basic.vo.UserVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.ArrayList;

@RestController
@RequestMapping("/api")
@Tag(name="User")
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("/users")
    @Operation(summary = "Get all users.")
    public BasicMsgWithData getAllUsers() {
        List<User> users = userService.getAllUsers();
        
        // 创建BasicMsgWithData对象并设置用户列表
        BasicMsgWithData msg = new BasicMsgWithData(users);
        msg.setErrorCode(GlobalEnum.ErrorCode.OK);
        msg.setErrorMsg("获取用户列表成功，共" + users.size() + "个用户。");
        msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
        return msg;
    }
    


    @PostMapping("/user")
    @Operation(summary = "Add a new user.")
    public BasicMsg addUser(@RequestBody UserVo user){
        BasicMsg msg = new BasicMsg();
        try {
            GlobalEnum.ErrorCode errorCode = userService.addUser(user);
            msg.setErrorCode(errorCode);
            if(errorCode == GlobalEnum.ErrorCode.OK){
                msg.setErrorMsg("添加用户成功。");
                msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
            } else if (errorCode == GlobalEnum.ErrorCode.USER_ALREADY_EXISTS) {
                msg.setErrorMsg("用户名已存在，请使用其他用户名。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            } else {
                msg.setErrorMsg("添加用户失败。");
                msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            }
        } catch (Exception e) {
            msg.setErrorCode(GlobalEnum.ErrorCode.UNKNOWN);
            msg.setErrorMsg("服务器异常: " + e.toString());
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
        }
        return msg;
    }

    //增加一个登录接口，让前端对接
    @PostMapping("/login")
    @Operation(summary = "Login.")
    public BasicMsg login(@RequestBody UserVo user){
        BasicMsg msg = new BasicMsg();
        GlobalEnum.ErrorCode errorCode = userService.userLogin(user.getUserName(), user.getPassword());
        msg.setErrorCode(errorCode);
        if(errorCode == GlobalEnum.ErrorCode.OK){
            msg.setErrorMsg("用户登录成功。");
            msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
        }else{
            msg.setErrorMsg("用户登录失败。");
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
        }
        return msg;
    }

    @DeleteMapping("/user/{username}")
    @Operation(summary = "Delete a user by username.")
    public BasicMsg deleteUser(@PathVariable String username){
        BasicMsg msg = new BasicMsg();
        GlobalEnum.ErrorCode errorCode = userService.deleteUserByUsername(username);
        msg.setErrorCode(errorCode);
        if(errorCode == GlobalEnum.ErrorCode.OK){
            msg.setErrorMsg("用户 " + username + " 删除成功。");
            msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
        } else if(errorCode == GlobalEnum.ErrorCode.USER_NOT_EXIST){
            msg.setErrorMsg("用户 " + username + " 不存在。");
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
        } else {
            msg.setErrorMsg("删除用户失败。");
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
        }
        return msg;
    }
    
    @PutMapping("/user/{username}")
    @Operation(summary = "Update a user by username.")
    public BasicMsg updateUserByUsername(@PathVariable String username, @RequestBody User user){
        BasicMsg msg = new BasicMsg();
        GlobalEnum.ErrorCode errorCode = userService.updateUserByUsername(username, user);
        msg.setErrorCode(errorCode);
        if(errorCode == GlobalEnum.ErrorCode.OK){
            msg.setErrorMsg("用户 " + username + " 信息更新成功。");
            msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
        } else if(errorCode == GlobalEnum.ErrorCode.USER_NOT_EXIST){
            msg.setErrorMsg("用户 " + username + " 不存在。");
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
        } else {
            msg.setErrorMsg("更新用户信息失败。");
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
        }
        return msg;
    }

    @GetMapping("/user/search")
    @Operation(summary = "Search for a user by username.")
    public BasicMsgWithData searchUserByUsername(@RequestParam String username) {
        BasicMsgWithData msg = new BasicMsgWithData();

        if (username == null || username.trim().isEmpty()) {
            msg.setErrorMsg("用户名不能为空。");
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
            return msg;
        }

        // 调用UserService查询用户
        User user = userService.getUserByUsername(username);

        if (user != null) {
            // 将单个用户对象包装在列表中
            List<User> userList = new ArrayList<>();
            userList.add(user);
            msg.setData(userList);
            msg.setErrorMsg("查询用户成功。");
            msg.setOperationResult(GlobalEnum.OperationResult.SUCC);
        } else {
            msg.setErrorMsg("未找到名为" + username + "的用户。");
            msg.setOperationResult(GlobalEnum.OperationResult.UNSUCC);
        }

        return msg;
    }

}
